package com.demo.study;

import org.openjdk.jol.info.ClassLayout;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: LockUpgrade
 * @Author : sz
 * @Date :2024/11/18  20:57
 * @Version :1.0
 */
public class LockUpgrade {

    public static void main(String[] args) throws InterruptedException {


        Object obj = new Object();
        System.out.println("无锁状态下" + ClassLayout.parseInstance(obj).toPrintable());
        TimeUnit.SECONDS.sleep(5);
        Object obj2 = new Object();
        System.out.println("偏向锁状态下" + ClassLayout.parseInstance(obj2).toPrintable());
        for (int i = 0; i < 2; i++) {
            synchronized (obj2) {
                System.out.println("偏向锁转轻量锁" + ClassLayout.parseInstance(obj2).toPrintable());
            }
            System.out.println("轻量锁释放" + ClassLayout.parseInstance(obj2).toPrintable());

        }
        new Thread(
                () -> {
                    synchronized (obj2) {
                        System.out.println("轻量锁" + ClassLayout.parseInstance(obj2).toPrintable());
                        try {
                            TimeUnit.SECONDS.sleep(5);
                        } catch (InterruptedException e) {

                        }
                        System.out.println("轻量锁转重量锁" + ClassLayout.parseInstance(obj2).toPrintable());
                    }
                }
        ).start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("重量锁1" + ClassLayout.parseInstance(obj2).toPrintable());
        new Thread(
                () -> {
                    synchronized (obj2) {
                        System.out.println("重量锁2" + ClassLayout.parseInstance(obj2).toPrintable());
                    }
                }
        ).start();
        TimeUnit.SECONDS.sleep(5);
        System.out.println("无状态锁" + ClassLayout.parseInstance(obj2).toPrintable());
    }
}
